<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkAgent\Command;

use Hyperf\Command\Annotation\Command;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Di\Annotation\Inject;
use MoChat\App\Corp\Contract\CorpContract;
use MoChat\App\Corp\Utils\WeWorkFactory;
use MoChat\App\WorkAgent\Contract\WorkAgentContract;
use Symfony\Component\Console\Input\InputArgument;

/**
 * @Command
 */
class FinishOpenIdMigrationCommand extends HyperfCommand
{
    /**
     * @Inject
     * @var WeWorkFactory
     */
    protected $weWorkFactory;

    /**
     * @Inject
     * @var CorpContract
     */
    protected $corpService;

    /**
     * @Inject
     * @var WorkAgentContract
     */
    protected $workAgentService;

    public function __construct()
    {
        parent::__construct('mochat:agent-migration');
    }

    public function handle()
    {
        $corpId = (int) $this->input->getArgument('corpId');
        $corp = $this->corpService->getCorpById($corpId);
        if (empty($corp)) {
            $this->error('企业不存在，请确认企业id输入是否正确');
            return;
        }

        $agent = $this->workAgentService->getWorkAgentCustomizedAppByCorpId($corpId);
        if (empty($agent)) {
            $this->error('应用不存在，请确认企业id输入是否正确');
            return;
        }

        $providerApp = $this->weWorkFactory->getProviderApp();

        $data = [
            'corpid' => $corp['wxCorpid'],
            'agentid' => (int) $agent['wxAgentId'],
            'openid_type' => [1, 3],
        ];
        $wxResult = $providerApp->provider->httpPostJson('/cgi-bin/service/finish_openid_migration', $data);
        if ($wxResult['errcode'] === 0) {
            $this->info('升级成功!');
        } else {
            $this->error('升级失败' . $wxResult['errmsg']);
        }
    }

    protected function configure()
    {
        parent::configure();
        $this->setDescription('代开发应用设置迁移完成');
        $this->addArgument('corpId', InputArgument::REQUIRED, '企业id');
    }
}
